import { ref, nextTick } from 'vue';
import { add, get, update } from '@/services';
import { message } from 'ant-design-vue';

export default function useAddEditModal(url, formState, search) {
  const isModalVisible = ref(false);
  const isEditing = ref(false);
  const formRef = ref(null);

  const showAddModal = () => {
    formRef.value?.resetFields();
    isModalVisible.value = true;
    isEditing.value = false;
  };

  const showEditModal = async id => {
    const res = await get(`/api/${url}`, id);
    if (res.success) {
      isModalVisible.value = true;
      isEditing.value = true;
      await nextTick(() => {
        Object.assign(formState, res.data);
      });
    }
  };

  const handleOk = async () => {
    try {
      await formRef.value.validate();
    } catch (error) {
      message.error('表单验证失败，请检查输入');
      return;
    }
    let res;
    if (isEditing.value) {
      res = await update(`/api/${url}`, formState);
    } else {
      res = await add(`/api/${url}`, formState);
    }

    const { success, data, msg } = res;

    if (success) {
      message.info(`操作成功`);
      isModalVisible.value = false;
      if (search) {
        await search();
      }
    } else {
      message.error(msg || `保存失败`);
    }
    return res;
  };

  const handleCancel = () => {
    isModalVisible.value = false;
  };

  const resetForm = () => {
    formRef.value?.resetFields();
  };

  return {
    isModalVisible,
    isEditing,
    formRef,

    showAddModal,
    showEditModal,

    handleOk,
    handleCancel,
    resetForm,
  };
}
